package com.sky.service.impl;

import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.EmployeeUpdatePasswordDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        // 将前端输入的密码进行md5加密后再与数据库中密码进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 新增员工
     *
     * @param employeeDTO
     */
    @Override
    public void save(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee); // 将dto中的数据cope给entity
        employee.setStatus(StatusConstant.ENABLE);  // 设置账号启用状态，默认为启用
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes())); // 设置默认密码并使用MD5加密
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
        // 从threadLocal中取出登录者的id
//        employee.setCreateUser(BaseContext.getCurrentId());
//        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.insert(employee);
    }

    /**
     * 根据姓名条件分页模糊查询
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public List<Employee> pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        List<Employee> employees = employeeMapper.pageQuery(employeePageQueryDTO);
        return employees;
    }

    /**
     * 禁用或者启用员工账号
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Integer id) {
        Employee employee = Employee.builder()
                .id(id.longValue())
                .status(status)
                .build();
        employeeMapper.update(employee);
    }

    /**
     * 根据id查询员工信息
     * @param id
     * @return
     */
    @Override
    public Employee getById(Long id) {
       Employee employee = employeeMapper.getById(id);
       return employee;
    }

    /**
     * 更新员工信息
     * @param employeeDTO
     */
    @Override
    public void updateEmployee(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO,employee); // 将dto转换为JavaBean
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.update(employee);
    }

    /**
     * 修改员工密码
     * @param employeeUpdatePasswordDTO
     */
    @Override
    public void updateEmployee(EmployeeUpdatePasswordDTO employeeUpdatePasswordDTO) {
        Employee employee = new Employee();
        // 将EmployeeUpdatePasswordDTO转换为JavaBean
        // 由于employeeUpdatePasswordDTO中的为empId，employee中的为id，二者不匹配无法使用该方法进行copy
//        BeanUtils.copyProperties(employeeUpdatePasswordDTO,employee);

        employee.setId(employeeUpdatePasswordDTO.getEmpId());
        String newPassword = employeeUpdatePasswordDTO.getNewPassword();
        // 将新密码进行md5加密
        employee.setPassword(DigestUtils.md5DigestAsHex(newPassword.getBytes()));
//        employee.setUpdateUser(BaseContext.getCurrentId());
//        employee.setUpdateTime(LocalDateTime.now());
        employeeMapper.update(employee);
    }
}
